package org.xmlpersist.dao;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.StringTokenizer;

/***
 * CommonDAO has methods which are common to all database, uncommon methods will
 * be in specific DAO classes
 * 
 * @author rjinoy
 * 
 */
public class CommonDao implements DBDao {

	private Connection conn;

	private Statement statement;

	private DatabaseMetaData dbmetadata;

	public final String CREATE_TABLE = "create table";

	public CommonDao(Connection connection) {
		this.conn = connection;
		try {
			statement = conn.createStatement();
			dbmetadata = conn.getMetaData();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	public void save(String insertQuery) {
		StringTokenizer tokens = new StringTokenizer(insertQuery, "#");
		while(tokens.hasMoreTokens()){
			String query = tokens.nextToken();
			try {
				statement.execute(query);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	public void createTable(String createQuery) {
		String query = CREATE_TABLE + " " + createQuery;
		try {
			statement.execute(query);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	
	public void setConnection(Connection connection) {
		conn = connection;
	}

	public boolean hasTable(String tableName) {
		try {
			ResultSet rs = dbmetadata.getTables(null, null, tableName, null);
			return rs.next();

		} catch (SQLException e) {
			e.printStackTrace();
		}
		return false;
	}
}
